//
//  NWRefreshControl.swift
//  Weibo
//
//  Created by Northwan on 16/1/28.
//  Copyright © 2016年 cn.northwan. All rights reserved.
//

import UIKit

/// 控件高度
let NWRefreshControlH:CGFloat = 50

class NWRefreshControl: UIControl {

    /**
     定义不同的状态
     
     - Normal:     默认
     - Pulling:    下拉
     - Refreshing: 刷新
     */
    enum NWRefreshControlState :Int{
        case Normal = 0
        case Pulling = 1
        case Refreshing = 2
    }
    
    //记录上一次刷新的状态
    var oldState:NWRefreshControlState = .Normal
    
    /// 当前控件所处于的状态
    var mState:NWRefreshControlState = .Normal{
        didSet{
            switch mState{
                case .Normal:
                    printLog("默认状态")
                    stateLabel.text = "下拉刷新"
                    arrowIcon.hidden = false
                    indicator.stopAnimating()
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.arrowIcon.transform = CGAffineTransformIdentity
                    })
                
                    if oldState == .Refreshing {
                        UIView.animateWithDuration(0.25, animations: { () -> Void in
                            var contentInset = self.scrollView!.contentInset
                            contentInset.top -= NWRefreshControlH
                            self.scrollView?.contentInset = contentInset
                        })
                    }
                case .Pulling:
                    printLog("释放刷新")
                    stateLabel.text = "释放刷新"
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    })
                case .Refreshing:
                    printLog("刷新中...")
                    stateLabel.text = "刷新中..."
                    arrowIcon.hidden = true
                    indicator.startAnimating()
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top += NWRefreshControlH
                        self.scrollView?.contentInset = contentInset
                    })
                
                    sendActionsForControlEvents(UIControlEvents.ValueChanged)
            }
            //记录状态
            oldState = mState
        }
    }

    var scrollView:UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //开始刷新
    func beginRefreshing(){
        mState = .Pulling
    }
    
    //结束刷新
    func endRefreshing(){
        mState = .Normal
    }

    private func setupUI(){
        
        addSubview(arrowIcon)
        addSubview(stateLabel)
        addSubview(indicator)
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self.centerY)
            make.centerX.equalTo(self.centerX).offset(-35)
        }
        
        stateLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(arrowIcon.snp_trailing).offset(10)
            make.centerY.equalTo(arrowIcon)
        }
        
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
        var frame =  self.frame
        frame.size.height = NWRefreshControlH
        frame.origin.y = -NWRefreshControlH
        self.frame = frame

        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        if let scrollView = newSuperview as? UIScrollView{
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
            self.scrollView = scrollView
            
            var frame =  self.frame
            frame.size.width = scrollView.size.width
            self.frame = frame
        }
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //判断并设置当前的状态
        
        if scrollView!.dragging {//scrollView拖动
            //移动的y值
            let contentOffsetY =  scrollView!.contentOffset.y
            
            //顶部的inset间距
            let contentInsetTop:CGFloat = scrollView!.contentInset.top
            
            //临界值，（当前控件完全显示出来的时候）
            let conditionValue = (-contentInsetTop-NWRefreshControlH)
            
            if mState == .Normal && contentOffsetY < conditionValue {
                //释放刷新状态
                mState = .Pulling
            }else if mState == .Pulling && contentOffsetY >= conditionValue{
                //默认状态
                mState = .Normal
            }
        }else{//scrollView释放
            if mState == .Pulling {//如果已经是释放刷新状态，就进入刷新状态
                mState = .Refreshing
            }
        }
        
    }
    
    // MARK: - 懒加载控件
    private lazy var arrowIcon:UIImageView = UIImageView(image: UIImage(named:"tableview_pull_refresh"))
    //状态文字
    private lazy var stateLabel:UILabel = UILabel(text: "下拉刷新", textColor: UIColor.grayColor(), fontSize: 14)
    //菊花
    private lazy var indicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:.Gray)
    
    
    deinit{
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
